<template>
  <!-- 搜索 -->
  <ContentWrap>
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="订单状态" prop="status">
            <el-select v-model="queryParams.status" clearable placeholder="全部">
              <el-option
                v-for="dict in statusTabs"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="订单来源" prop="source">
            <el-select
              v-model="queryParams.source"
              @change="handleSourceChange"
              clearable
              placeholder="全部"
            >
              <el-option
                v-for="dict in sourceList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4" v-if="queryParams.source">
          <el-form-item label="销售门店" prop="tenantIds">
            <template #label>
              销售{{
                sourceList.find((item) => {
                  return item.value == queryParams.source
                })?.label
              }}
            </template>
            <el-select v-model="queryParams.tenantIds" clearable multiple placeholder="全部">
              <el-option
                v-for="item in tenantList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="销售员工" prop="employeeName">
            <el-select v-model="queryParams.employeeName" clearable placeholder="全部">
              <el-option
                v-for="item in employeeList"
                :key="item.employeeId"
                :label="item.employeeName"
                :value="item.employeeId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="支付方式" prop="payChannelCode">
            <el-select v-model="queryParams.payChannelCode" clearable placeholder="全部">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.PAY_CHANNEL_CODE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="销售时间" prop="tradeTime">
            <el-date-picker
              v-model="queryParams.tradeTime"
              :shortcuts="defaultShortcuts"
              :disabled-date="disabledDate"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              end-placeholder="自定义时间"
              start-placeholder="自定义时间"
              type="daterange"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              :shortcuts="defaultShortcuts"
              :disabled-date="disabledDate"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              end-placeholder="自定义时间"
              start-placeholder="自定义时间"
              type="daterange"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="订单渠道" prop="terminal">
            <el-select v-model="queryParams.terminal" clearable placeholder="全部">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.TERMINAL)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="订单类型" prop="type">
            <el-select v-model="queryParams.type" clearable placeholder="全部">
              <el-option
                v-for="dict in tradeOrderType"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="配送方式" prop="deliveryType">
            <el-select v-model="queryParams.deliveryType" clearable placeholder="全部">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.TRADE_DELIVERY_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
          :xl="4"
          v-if="queryParams.deliveryType === DeliveryTypeEnum.EXPRESS.type"
        >
          <el-form-item label="快递公司" prop="logisticsId">
            <el-select v-model="queryParams.logisticsId" clearable placeholder="全部">
              <el-option
                v-for="item in deliveryExpressList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
          :xl="4"
          v-if="queryParams.deliveryType === DeliveryTypeEnum.PICK_UP.type"
        >
          <el-form-item label="自提门店" prop="pickUpStoreId">
            <el-select v-model="queryParams.pickUpStoreId" clearable multiple placeholder="全部">
              <el-option
                v-for="item in pickUpStoreList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col
          :xs="24"
          :sm="12"
          :md="8"
          :lg="6"
          :xl="4"
          v-if="queryParams.deliveryType === DeliveryTypeEnum.PICK_UP.type"
        >
          <el-form-item label="核销码" prop="pickUpVerifyCode">
            <el-input
              v-model="queryParams.pickUpVerifyCode"
              clearable
              placeholder="请输入自提核销码"
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="订单标记" prop="mark">
            <el-select v-model="queryParams.mark" clearable>
              <el-option
                v-for="dict in markColorList"
                :key="dict.mark"
                :label="dict.label"
                :value="dict.mark"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="代理" prop="agentName">
            <el-input v-model="queryParams.agentName" clearable placeholder="请输入代理名称" />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="聚合搜索">
            <el-input
              v-show="true"
              v-model="queryParams[queryType.queryParam]"
              :type="queryType.queryParam === 'userId' ? 'number' : 'text'"
              clearable
              placeholder="请输入"
            >
              <template #prepend>
                <el-select
                  v-model="queryType.queryParam"
                  class="!w-100px"
                  clearable
                  placeholder="全部"
                  @change="inputChangeSelect"
                >
                  <el-option
                    v-for="dict in dynamicSearchList"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="排序方式" prop="sortType">
            <div class="flex w-full!">
              <div class="flex-1">
                <el-select v-model="queryParams.sortType" class="w-100%!" clearable>
                  <el-option
                    v-for="dict in getIntDictOptions(DICT_TYPE.TRADE_ORDER_SORT_TYPE)"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </div>
              <div class="flex ml-10px">
                <el-radio-group v-model="queryParams.sortStatus" @change="handleQuery">
                  <el-radio-button label="正序" value="up">
                    <div class="flex"><Icon icon="ep:top" :size="14" /> </div>
                  </el-radio-button>
                  <el-radio-button label="倒序" value="down">
                    <div class="flex"><Icon icon="ep:bottom" :size="14" /> </div>
                  </el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="4">
          <el-form-item>
            <el-button @click="handleQuery">
              <Icon class="mr-5px" icon="ep:search" />
              搜索
            </el-button>
            <el-button @click="resetQuery">
              <Icon class="mr-5px" icon="ep:refresh" />
              重置
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </ContentWrap>

  <!-- 统计卡片 -->
  <el-row :gutter="10">
    <el-col :xl="6" :lg="6" :md="6" :sm="24" :xs="24" v-loading="loading">
      <SummaryCard
        title="订单数量"
        class="mb-10px"
        icon="icon-park-outline:transaction-order"
        icon-color="bg-blue-100"
        icon-bg-color="text-blue-500"
        :value="summary?.orderCount || 0"
      />
    </el-col>
    <el-col :xl="6" :lg="6" :md="6" :sm="24" :xs="24" v-loading="loading">
      <SummaryCard
        title="下单人数"
        class="mb-10px"
        icon="icon-park-outline:transaction-order"
        icon-color="bg-blue-100"
        icon-bg-color="text-blue-500"
        :value="summary?.orderUser || 0"
      />
    </el-col>
    <el-col :xl="6" :lg="6" :md="6" :sm="24" :xs="24" v-loading="loading">
      <SummaryCard
        title="订单金额"
        class="mb-10px"
        icon="streamline:money-cash-file-dollar-common-money-currency-cash-file"
        icon-color="bg-purple-100"
        icon-bg-color="text-purple-500"
        prefix="￥"
        :decimals="2"
        :value="Number(fenToYuan(summary?.orderTotalPrice || 0))"
      />
    </el-col>
    <el-col :xl="6" :lg="6" :md="6" :sm="24" :xs="24" v-loading="loading">
      <SummaryCard
        title="订单实售"
        class="mb-10px"
        icon="streamline:money-cash-file-dollar-common-money-currency-cash-file"
        icon-color="bg-purple-100"
        icon-bg-color="text-purple-500"
        prefix="￥"
        :decimals="2"
        :value="Number(fenToYuan(summary?.orderRealPrice || 0))"
      />
    </el-col>
    <el-col :xl="6" :lg="6" :md="6" :sm="24" :xs="24" v-loading="loading">
      <SummaryCard
        title="实付金额"
        class="mb-10px"
        icon="mdi:cash-plus"
        icon-color="bg-purple-100"
        icon-bg-color="text-purple-500"
        prefix="￥"
        :decimals="2"
        :value="Number(fenToYuan(summary?.orderPayPrice || 0))"
      />
    </el-col>
    <el-col :xl="6" :lg="6" :md="6" :sm="24" :xs="24" v-loading="loading">
      <SummaryCard
        title="资产抵扣"
        class="mb-10px"
        icon="mdi:cash-sync"
        icon-color="bg-purple-100"
        icon-bg-color="text-purple-500"
        prefix="￥"
        :decimals="2"
        :value="Number(fenToYuan(summary?.orderCartPrice || 0))"
      />
    </el-col>
    <el-col :xl="6" :lg="6" :md="6" :sm="24" :xs="24" v-loading="loading">
      <SummaryCard
        title="欠款金额"
        class="mb-10px"
        icon="mdi:cash-minus"
        icon-color="bg-purple-100"
        icon-bg-color="text-purple-500"
        prefix="￥"
        :decimals="2"
        :value="Number(fenToYuan(summary?.arrearsPrice || 0))"
      />
    </el-col>

    <el-col :xl="6" :lg="6" :md="6" :sm="24" :xs="24" v-loading="loading">
      <SummaryCard
        title="退款金额"
        class="mb-10px"
        icon="ri:refund-2-line"
        icon-color="bg-green-100"
        icon-bg-color="text-green-500"
        prefix="￥"
        :decimals="2"
        :value="Number(fenToYuan(summary?.afterSalePrice || 0))"
      />
    </el-col>
  </el-row>
  <!-- 列表 -->

  <ContentWrap>
    <el-tabs v-model="queryParams.status" @tab-click="handleQuery">
      <el-tab-pane
        v-for="item in statusTabs"
        :key="item.value"
        :label="item.label"
        :name="item.value"
      >
        <template #label>
          <span>{{ `${item.label} (${summary?.statusMap[`order${item.value}`] || 0})` }}</span>
        </template>
      </el-tab-pane>
    </el-tabs>

    <!-- 添加 row-key="id" 解决列数据中的 table#header 数据不刷新的问题  -->
    <el-table
      v-loading="loading"
      :data="list"
      row-key="id"
      :cell-style="{ padding: 0, borderBottom: 'none' }"
      :header-cell-style="{ padding: 0 }"
      :row-class-name="'table-row-class'"
    >
      <OrderTableColumn :list="list" :pick-up-store-list="pickUpStoreList">
        <template #rightOperate="{ row }">
          <div class="flex justify-end cursor-pointer">
            <el-link @click="handleUploadCertificate(row)"
              ><Icon
                icon="svg-icon:order_pingzheng"
                :class="{ 'c-[var(--el-color-primary)]!': false }"
                class="font-size-20px!"
            /></el-link>
            <el-link class="ml-5px">
              <el-popover placement="top" title="设置标记" :width="200" trigger="click">
                <template #default>
                  <Icon
                    icon="svg-icon:order_tag"
                    v-for="(tag, index) in markColorList"
                    :key="index"
                    :color="tag.color"
                    @click="handleSetTag(row, tag)"
                    class="font-size-20px! cursor-pointer ml-10px"
                  />
                </template>
                <template #reference>
                  <Icon
                    icon="svg-icon:order_tag"
                    :color="
                      markColorList.find((ele) => {
                        return ele.mark == row.mark
                      })?.color
                    "
                    class="font-size-20px!"
                  />
                </template>
              </el-popover>
            </el-link>
          </div>
        </template>
        <template #default="{ row }">
          <div class="flex items-center justify-center">
            <el-button
              v-hasPermi="['trade:order:query']"
              link
              type="primary"
              @click="openDetail(row.id)"
            >
              <Icon icon="ep:notification" />
              详情
            </el-button>
            <el-dropdown
              v-hasPermi="['trade:order:update']"
              @command="(command) => handleCommand(command, row)"
            >
              <el-button link type="primary">
                <Icon icon="ep:d-arrow-right" />
                更多
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="cancel">
                    <Icon icon="ep:chat-line-square" />
                    撤销订单
                  </el-dropdown-item>
                  <!--  <el-dropdown-item command="">
                    <Icon icon="ep:chat-line-square" />
                    打印小票
                  </el-dropdown-item> -->
                  <el-dropdown-item command="">
                    <Icon icon="ep:chat-line-square" />
                    申请退款
                  </el-dropdown-item>
                  <el-dropdown-item
                    command="updatePrice"
                    v-if="row.status! === TradeOrderStatusEnum.UNPAID.status"
                  >
                    <Icon icon="ep:chat-line-square" />
                    订单改价
                  </el-dropdown-item>
                  <el-dropdown-item
                    command="onPay"
                    v-if="row.status! === TradeOrderStatusEnum.UNPAID.status"
                  >
                    <Icon icon="ep:chat-line-square" />
                    继续支付
                  </el-dropdown-item>
                  <!-- <el-dropdown-item command="">
                    <Icon icon="ep:chat-line-square" />
                    线下支付
                  </el-dropdown-item> -->
                  <el-dropdown-item command="logs">
                    <Icon icon="ep:chat-line-square" />
                    订单日志
                  </el-dropdown-item>
                  <!-- 如果是【快递】，并且【未发货】，则展示【发货】按钮 -->
                  <el-dropdown-item
                    v-if="
                      row.deliveryType === DeliveryTypeEnum.EXPRESS.type &&
                      row.status === TradeOrderStatusEnum.UNDELIVERED.status
                    "
                    command="delivery"
                  >
                    <Icon icon="ep:takeaway-box" />
                    订单发货
                  </el-dropdown-item>
                  <el-dropdown-item command="remark">
                    <Icon icon="ep:chat-line-square" />
                    订单备注
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </OrderTableColumn>
      <template #empty>
        <Empty />
      </template>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 支付弹框 -->
  <PayDialog
    ref="payDialogRef"
    :no="state.no"
    :dialog-visible="state.showPayDialog"
    :payment-map="state.paymentMap"
    :order-info="state.orderInfo"
    :scene-type="'second'"
    @success="handleUpdate"
    @close="
      () => {
        state.showPayDialog = false
      }
    "
  />

  <!-- 各种操作的弹窗 -->
  <OrderDeliveryForm ref="deliveryFormRef" @success="getList" />
  <OrderUpdateRemarkForm ref="updateRemarkForm" @success="getList" />
  <OrderUpdatePriceForm ref="updatePriceFormRef" @success="getList" />
  <OrderCancelRemarkForm ref="cancelRemarkFormRef" @success="getList" />
  <OrderUpTransactionVoucherForm ref="upTransactionVoucherFormRef" @success="getList" />
</template>

<script lang="ts" setup>
import type { FormInstance } from 'element-plus'
import OrderDeliveryForm from '@/views/mall/trade/order/form/OrderDeliveryForm.vue'
import OrderUpdateRemarkForm from '@/views/mall/trade/order/form/OrderUpdateRemarkForm.vue'
import OrderUpdatePriceForm from '@/views/mall/trade/order/form/OrderUpdatePriceForm.vue'
import OrderUpTransactionVoucherForm from '@/views/mall/trade/order/form/OrderUpTransactionVoucherForm.vue'
import OrderCancelRemarkForm from '@/views/mall/trade/order/form/OrderCancelRemarkForm.vue' //订单撤销
import PayDialog from '@/views/shop/components/payDialog/index.vue' //支付弹框
import * as TradeOrderApi from '@/api/mall/trade/order'
import * as PickUpStoreApi from '@/api/mall/trade/delivery/pickUpStore'
import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import * as DeliveryExpressApi from '@/api/mall/trade/delivery/express'
import { DeliveryTypeEnum, TradeOrderStatusEnum } from '@/utils/constants'
import { OrderTableColumn } from './components'
import { appendEmployee, fenToYuan } from '@/utils'
import SummaryCard from '@/components/SummaryCard/index.vue'
import { defaultShortcuts } from '@/utils/formatTime'
/**时间范围限制 */
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}
defineOptions({ name: 'TradeOrder' })
const message = useMessage() // 消息弹窗
const { currentRoute, push } = useRouter() // 路由跳转
const loading = ref(true) // 列表的加载中
// const exportLoading = ref(false) // 导出的加载中
const total = ref(2) // 列表的总页数
const list = ref<TradeOrderApi.OrderVO[]>([]) // 列表的数据
const queryFormRef = ref<FormInstance>() // 搜索的表单
const summary = ref<TradeOrderApi.TradeOrderSummaryRespVO>() // 订单统计数据
//标记列表
const markColorList = [
  {
    label: '取消',
    color: '',
    mark: 0
  },
  {
    label: '红色',
    color: '#FF0000',
    mark: 1
  },
  {
    label: '黄色',
    color: '#FFFF00',
    mark: 2
  },
  {
    label: '蓝色',
    color: '#0000FF',
    mark: 3
  },
  {
    label: '绿色',
    color: '#00FF00',
    mark: 4
  }
]
// 交易订单类型
const tradeOrderType = ref([
  {
    label: '普通订单',
    value: 0
  },
  {
    label: '秒杀订单',
    value: 1
  },
  {
    label: '砍价订单',
    value: 2
  },
  {
    label: '拼团订单',
    value: 3
  },
  {
    label: '积分商城',
    value: 4
  },
  {
    label: '活动订单',
    value: 6
  },
  {
    label: '超级拼团订单',
    value: 20
  }
])
// 交易订单来源
const sourceList = ref([
  {
    label: '门店',
    value: 4
  },
  {
    label: '商城',
    value: 5
  }
])
// 销售门店或商城 选择列表
import * as TenantApi from '@/api/system/tenant'
const tenantList = ref<any>([])
const handleSourceChange = async () => {
  queryParams.value.tenantIds = undefined
  tenantList.value = []
  if (queryParams.value.source) {
    let params = {
      tenantType: queryParams.value.source
    }
    const data = await TenantApi.getChildTenantWithPostList(params)

    data.map((ele) => {
      tenantList.value.push({
        name: ele.name,
        id: ele.id
      })
    })
  }
}
// 销售员工选择列表
import * as UserApi from '@/api/shop/system/user/index'

const employeeList = ref<any>([])
const getEmployeeList = async () => {
  const data = await UserApi.getEmployeeList()
  employeeList.value = data
}

// 表单搜索
const queryParams = ref({
  typeClass: 0, //订单分类 0 销售订单（默认）
  pageNo: 1, // 页数
  pageSize: 10, // 每页显示数量
  status: '', // 订单状态
  payChannelCode: undefined, // 支付方式
  tradeTime: undefined, //销售时间
  createTime: undefined, // 创建时间
  terminal: undefined, // 订单渠道
  source: undefined, //订单来源
  type: undefined, // 订单类型
  deliveryType: undefined, // 配送方式
  logisticsId: undefined, // 快递公司
  pickUpStoreId: undefined, // 自提门店
  pickUpVerifyCode: undefined, // 自提核销码
  tenantIds: undefined, //销售门店
  employeeName: undefined, //销售员工
  agentName: undefined, //代理名称
  mark: undefined,
  sortType: 0, //排序类型
  sortStatus: 'up' //排序状态
})
const queryType = reactive({ queryParam: 'no' }) // 订单搜索类型 queryParam
// 订单聚合搜索 select 类型配置（动态搜索）
const dynamicSearchList = ref([
  { value: 'no', label: '订单号' },
  { value: 'userId', label: '用户UID' },
  { value: 'userNickname', label: '姓名昵称' },
  { value: 'userMobile', label: '用户电话' }
])
/**
 * 聚合搜索切换查询对象时触发
 * @param val
 */
const inputChangeSelect = (val: string) => {
  dynamicSearchList.value
    .filter((item) => item.value !== val)
    ?.forEach((item1) => {
      // 清除集合搜索无用属性
      if (queryParams.value.hasOwnProperty(item1.value)) {
        delete queryParams.value[item1.value]
      }
    })
}

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 统计
    summary.value = await TradeOrderApi.getOrderSummary(unref(queryParams))
    const data = await TradeOrderApi.getOrderPage(unref(queryParams))
    list.value = data.list
    // 处理单一销售员工时 列表展示问题,将单一销售员工 合并到 订单列表中
    appendEmployee(list)
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = async () => {
  nextTick(async () => {
    queryParams.value.pageNo = 1
    await getList()
  })
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  queryParams.value = {
    pageNo: 1, // 页数
    pageSize: 10, // 每页显示数量
    status: '', // 订单状态
    payChannelCode: undefined, // 支付方式
    tradeTime: undefined, //销售时间
    createTime: undefined, // 创建时间
    terminal: undefined, // 订单来源
    type: undefined, // 订单类型
    deliveryType: undefined, // 配送方式
    logisticsId: undefined, // 快递公司
    pickUpStoreId: undefined, // 自提门店
    pickUpVerifyCode: undefined, // 自提核销码
    mark: undefined,
    typeClass: 0,
    employeeName: undefined,
    source: undefined,
    agentName: undefined,
    tenantIds: undefined,
    sortType: 0, //排序类型
    sortStatus: 'up' //排序状态
  }
  handleQuery()
}
/** 导出按钮操作
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await TradeOrderApi.export(queryParams)
    download.excel(data, '订单列表.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
 */
/** 查看订单详情 */
const openDetail = (id: number) => {
  console.log(id)
  push({ name: 'TradeOrderDetail', params: { id } })
}

/** 操作分发 */

const deliveryFormRef = ref()
const updateRemarkForm = ref()
const updatePriceFormRef = ref() // 订单调价表单 Ref
const upTransactionVoucherFormRef = ref()
const cancelRemarkFormRef = ref()
const handleCommand = (command: string, row: TradeOrderApi.OrderVO) => {
  switch (command) {
    case 'updatePrice':
      updatePriceFormRef.value?.open(row)
      break
    case 'logs':
      openDetail(row.id as number)
      break
    case 'remark':
      updateRemarkForm.value?.open(row)
      break
    case 'cancel':
      cancelRemarkFormRef.value?.open(row)
      break
    case 'delivery':
      deliveryFormRef.value?.open(row)
      break
    case 'onPay':
      state.userId = row.user?.id
      state.no = row.no
      state.payOrderId = row.payOrderId
      getOrderInfo()

      break
  }
}
// 检查库存 & 计算订单价格 继续支付
import * as OrderApi from '@/api/shop/trade/order'
const state = reactive({
  showCoupon: false, // 是否展示优惠劵
  couponInfo: [], // 优惠劵列表
  userId: '' as any, // 会员id
  no: '' as any, //订单号
  orderInfo: {},
  // ========== 员工 ==========
  // 会员资产支付
  paymentMap: [],
  pay: [] as any,
  payOrderId: '', //支付订单号
  showPayDialog: false //是否正在支付
})

const handleUpdate = () => {
  ElNotification({
    title: '提示',
    message: '订单完成',
    type: 'success'
  })
  state.showPayDialog = false
  getList()
}
const getOrderInfo = async () => {
  // 计算价格
  const data = await OrderApi.secondSettlementOrder({
    userId: state.userId,
    payOrderId: state.payOrderId
  } as any)
  state.orderInfo = data

  state.paymentMap = data.paymentMap

  openPayDialog()
}

/** 支付弹框 */
const payDialogRef = ref()
const openPayDialog = () => {
  // payDialogRef.value.open()
  state.showPayDialog = true
}

/** 上传凭证弹窗 */
const handleUploadCertificate = (row) => {
  upTransactionVoucherFormRef.value.open(row)
}
/** 设置标签弹框 */
const handleSetTag = async (row, tag) => {
  let params = {
    id: row.id,
    mark: tag.mark
  }
  const data = await TradeOrderApi.updateOrderMark(params)
  if (data) {
    message.success('标记成功')
    getList()
  }
}

// 监听路由变化更新列表，解决订单保存/更新后，列表不刷新的问题。
watch(
  () => currentRoute.value,
  () => {
    getList()
  }
)

const pickUpStoreList = ref<PickUpStoreApi.DeliveryPickUpStoreVO[]>([]) // 自提门店精简列表
const deliveryExpressList = ref<DeliveryExpressApi.DeliveryExpressVO[]>([]) // 物流公司
const statusTabs = ref([
  {
    label: '全部',
    value: ''
  },
  {
    label: '待支付',
    value: 0
  },
  {
    label: '已支付',
    value: 2
  },
  {
    label: '待成团',
    value: 4
  },
  {
    label: '待发货',
    value: 10
  },
  {
    label: '已发货',
    value: 20
  },
  {
    label: '已完成',
    value: 30
  },
  {
    label: '已取消',
    value: 40
  },
  {
    label: '已撤销',
    value: 50
  },
  {
    label: '待评价',
    value: 60
  },
  {
    label: '有欠款',
    value: 70
  },
  {
    label: '待核销',
    value: 80
  },
  {
    label: '到店付',
    value: 90
  },
  {
    label: '已核销',
    value: 100
  }
])
/** 初始化 **/
onMounted(async () => {
  await getList()
  pickUpStoreList.value = await PickUpStoreApi.getListAllSimple()
  deliveryExpressList.value = await DeliveryExpressApi.getSimpleDeliveryExpressList()
  await getEmployeeList()
  // 设置 statuses 过滤
  // for (const dict of getDictOptions(DICT_TYPE.TRADE_ORDER_STATUS)) {
  //   statusTabs.value.push({
  //     label: dict.label,
  //     value: dict.value
  //   })
  // }
})
</script>
<style lang="scss" scoped>
.sort-select {
  :deep(.el-select__wrapper) {
    height: 40px;
  }
}
:deep(.order-table-col > .cell) {
  padding: 0;
}
:deep(.table-row-class) {
  --el-table-row-hover-bg-color: transparent;
}
</style>
